tab sh_p_w
tab sh_ud_w
tab sh_ud_p
tab sh_udd_w
tab sh_as_w
tab sh_ud_p
tab sh_udd_p
tab sh_as_p
tab sh_udd_ud
tab sh_as_ud
tab sh_as_udd

gen big_N=_n

local VAR big_N UD_num b_id s_id  
foreach v of local VAR{
distinct `v' if woven==1 
distinct `v' if selected_p==1 
distinct `v' if  (selected_p==1 & no_UDs==0)
distinct `v' if  (selected_p==1 & no_UDs==0 & S_pd==1)
distinct `v' if  (S_pds==1) 
}

local P b s 
foreach p of local P{

capture drop  n_`p'
bys `p'_id: gen n_`p'=_n

bys `p'_id: egen q_`p'=total(q_exp)
bys `p'_id: egen pq_`p'=total(pq_exp) 
gen p_`p'=pq_`p'/q_`p' 

capture drop SAMPLE
gen SAMPLE=( woven==1 )
bys `p'_id: egen `p'_in_1_sample=max(SAMPLE)
eststo O_TB1_B1_q_`p': estpost tabstat q_`p' if  n_`p'==1 & `p'_in_1_sample,  statistics(N mean sd p10 p25 median p75 p90)  
eststo O_TB1_B1_p_`p': estpost tabstat p_`p' if  n_`p'==1 & `p'_in_1_sample,  statistics(N mean sd p10 p25 median p75 p90)  

capture drop SAMPLE
gen SAMPLE=( selected_p==1 )
bys `p'_id: egen `p'_in_2_sample=max(SAMPLE)
eststo O_TB1_B2_q_`p': estpost tabstat q_`p' if  n_`p'==1 & `p'_in_2_sample,  statistics(N mean sd p10 p25 median p75 p90) 
eststo O_TB1_B2_p_`p': estpost tabstat p_`p' if  n_`p'==1 & `p'_in_2_sample,  statistics(N mean sd p10 p25 median p75 p90)  

capture drop SAMPLE
gen SAMPLE=((selected_p & no_UDs==0))
bys `p'_id: egen `p'_in_3_sample=max(SAMPLE)
eststo O_TB1_B3_q_`p': estpost tabstat q_`p' if  n_`p'==1 & `p'_in_3_sample,  statistics(N mean sd p10 p25 median p75 p90)  
eststo O_TB1_B3_p_`p': estpost tabstat p_`p' if  n_`p'==1 & `p'_in_3_sample,  statistics(N mean sd p10 p25 median p75 p90)  


capture drop SAMPLE
gen SAMPLE=(selected_p==1 & no_UDs==0 & S_pd==1==1)
bys `p'_id: egen `p'_in_4_sample=max(SAMPLE)
eststo O_TB1_B4_q_`p': estpost tabstat q_`p' if  n_`p'==1 & `p'_in_4_sample,  statistics(N mean sd p10 p25 median p75 p90)  
eststo O_TB1_B4_p_`p': estpost tabstat p_`p' if  n_`p'==1 & `p'_in_4_sample,  statistics(N mean sd p10 p25 median p75 p90) 

capture drop SAMPLE
gen SAMPLE=( S_pds==1)
bys `p'_id: egen `p'_in_5_sample=max(SAMPLE)
eststo O_TB1_B5_q_`p': estpost tabstat q_`p' if  n_`p'==1 & `p'_in_5_sample,  statistics(N mean sd p10 p25 median p75 p90)  
eststo O_TB1_B5_p_`p': estpost tabstat p_`p' if  n_`p'==1 & `p'_in_5_sample,  statistics(N mean sd p10 p25 median p75 p90) 
 
}

esttab O_*_q_* O_*_p_* using "${tables}\TableB1PanelB.tex", cells("count(fmt(%9.0gc)) mean(fmt(a2)) sd(fmt(a2)) p10(fmt(a2)) p25(fmt(a2)) p50(fmt(a2)) p75(fmt(a2)) p90(fmt(a2))")  nomtitles label nonumbers noobs unstack replace posthead(" ") nodep collabels(none) prehead(" ") postfoot(" ")